#include "SList.h"


void SLTPrint(SLTNode* phead)
{
    SLTNode* cur = phead;
    while(cur)
    {
        printf("%d -> ",cur->data);
        cur = cur->next;
    }
    printf("NULL\n");
}


SLTNode* BuySListNode(SLTDataType x)
{
    SLTNode* newnode = (SLTNode*)malloc(sizeof(SLTNode));
    if(newnode == NULL)
    {
        perror("malloc fail");
        exit(-1);
    }   

    newnode->data = x;
    newnode->next = NULL;

    return newnode;
}

SLTNode* SLTFind(SLTNode* phead,SLTDataType x)
{
    SLTNode* cur = phead;
    while(cur)
    {
        if(cur->data == x)
        {
            return cur;
        }
        cur = cur->next;
    }
    return NULL;
}


void SLTPushBack(SLTNode** pphead,SLTDataType x)
{
    assert(pphead);
    SLTNode* newnode = BuySListNode(x);
    if(*pphead == NULL)
    {
        *pphead = newnode;
    }
    else
    {
        SLTNode* tail = *pphead;
        while(tail->next)//找尾节点
        {
            tail = tail->next;
        }
        tail->next = newnode;
    }
}

void SLTPopBack(SLTNode** pphead)
{
    assert(pphead);
    assert(*pphead);//检查链表是否为空
    if((*pphead)->next == NULL)//只有一个节点
    {
        free(*pphead);
        *pphead = NULL;
    }
    else//多个节点
    {
        SLTNode* tail = *pphead;
        while(tail->next->next)//找尾节点的上一个节点
        {
            tail = tail->next;
        }
        free(tail->next);
        tail->next = NULL;
    }
}

void SLTPushFront(SLTNode** pphead,SLTDataType x)
{
    assert(pphead);
    SLTNode* newnode = BuySListNode(x);
    newnode->next = *pphead;
    *pphead = newnode;
}

void SLTPopFront(SLTNode** pphead)
{
    assert(pphead);
    assert(*pphead);
    SLTNode* pheadnext = (*pphead)->next;
    free(*pphead);
    (*pphead) = pheadnext;
}

void SLTInsert(SLTNode** pphead,SLTNode* pos,SLTDataType x)
{
    assert(pphead);
    assert(*pphead);
    assert(pos);

    SLTNode* cur = *pphead;
    if(cur == pos)//头插
    {
        SLTPushFront(pphead,x);
    }
    else
    {
        while(cur->next != pos)//找pos前一个节点
        {
            cur = cur->next;
        }
        SLTNode* newnode = BuySListNode(x);
        cur->next = newnode;
        newnode->next = pos;
    }
}

void SLIInsertAfter(SLTNode* pos,SLTDataType x)
{
    assert(pos);
    SLTNode* newnode = BuySListNode(x);
    SLTNode* posnext = pos->next;
    newnode->next = posnext;
    pos->next = newnode;
}

void SLTErase(SLTNode** pphead,SLTNode* pos)
{
    assert(pphead);
    assert(*pphead);
    assert(pos);

    SLTNode* cur = *pphead;
    if(cur == pos)//头删
    {
        SLTPopFront(pphead);
    }
    else
    {
        while(cur->next != pos)//找pos前一个节点
        {
            cur = cur->next;
        }
        cur->next = pos->next;
        free(pos);
    }
}

void SLTEraseAfter(SLTNode* pos)
{
    assert(pos);
    assert(pos->next);//检查是否为尾节点
    SLTNode* del = pos->next;
    SLTNode* delnext = del->next;
    pos->next = delnext;
    free(del);
}
